package rmi.farted;

import java.awt.*;
import java.awt.event.*;

/** ModalDialog :- provides a simple question-and-answer dialog
 *
 *  <p>Usage:
 *  <pre>
 *  ModalDialog question = new ModalDialog(this,"question");
 *  question.setAnswer("default answer");
 *  question.show();
 *  name = question.getAnswer();
 *  </pre>
 * 
 * @version 1.0, October 2001
 * @author J. Schoch
 * @date 20102010
 */

public class ModalDialog extends Dialog implements ActionListener {
	private static final long serialVersionUID = 1L;
	private String answer = null;
	private TextField answerfield = null;
	private Fertig schluss = null;

	//----- common dialog box setup

	private void construct (String question, int width) {
		this.setTitle(question);
		answerfield = new TextField(width);
		answerfield.setBackground(new Color(255,255,150));
		this.add(answerfield,"Center");
		answerfield.addActionListener(this);
		answerfield.setFont(new Font("Monospaced",Font.BOLD,16));
		this.setBounds(100,100,1,1);
		this.pack();
		schluss = new Fertig(this);
	}

	/**
	 * @param f parent frame
	 * @param q question string
	 * @param w width of input text field, default=70
	 */
	public ModalDialog(Frame f, String q, int w) {
		super (f, true); construct(q,w);
	}

	public ModalDialog(Frame f, String q) {
		super (f, true); construct(q,70);
	}

	/**
	 * @param s preset answer text string; insertion point at end.
	 */
	public void setAnswer(String s) {
		answerfield.setText(s);
		if (s!=null) {answerfield.setCaretPosition(s.length());}
	}

	/**
	 *  Text entry is normally concluded by pressing the "Enter" key.<br>
	 *  If the dialog box frame gets closed by means of window controls, the
	 *  resulting answer will be <tt>null</tt>
	 *
	 * @return answer text string
	 */
	synchronized public String getAnswer() {return(answer);}

	//----- Listener for the "EnterKey" being typed
	synchronized public void actionPerformed(ActionEvent e) {
		if(e.getSource()==answerfield) {
			answer = answerfield.getText();
			dispose();
		}
	}

	//----- Window Adapter for the "closing" event
	class Fertig extends WindowAdapter {
		private ModalDialog d = null;
		Fertig(ModalDialog d) {this.d = d; d.addWindowListener(this);}
		public void windowClosing(WindowEvent e) {
			d.setAnswer(null);
			d.dispose();
		}
	} // Fertig

} // ModalDialog